/**
 * 
 */
package org.dragonfire.editor.z80.hiliteRules;

import org.dragonfire.editor.z80.AssemblyScanner;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;

/**
 * @author Darth Android
 * @date Oct 3, 2007
 */
public class CommandRule implements IRule {

	private IToken token;

	public CommandRule(IToken token) {
		this.token = token;
	}

	public IToken evaluate(ICharacterScanner scanner) {
		if (!(scanner instanceof AssemblyScanner))
			return Token.UNDEFINED;
		AssemblyScanner scan = (AssemblyScanner) scanner;
		if (!(scan.getLastMatchedRule() instanceof LabelRule) && !(scanner.getColumn() == 0))
			return Token.UNDEFINED;
		return doEvaluate(scanner, false);
	}

	public IToken doEvaluate(ICharacterScanner scanner, boolean seenText) {
		int i = scanner.read();
		if (i == ICharacterScanner.EOF) {
			scanner.unread();
			return seenText ? token : Token.UNDEFINED;
		}
		char c = (char) i;
		IToken t = Token.UNDEFINED;
		if (Character.isWhitespace(c))
			if (seenText) {
				scanner.unread();
				t = token;
			}
			else
				t = doEvaluate(scanner, false);
		else if (!Character.isWhitespace(c))
			t = doEvaluate(scanner, true);
		if (t == Token.UNDEFINED)
			scanner.unread();
		return t;
	}
}
